'''※※※※※※※※※※※※※※※※※※※※※※※※※※※※※※※※※※※※※※※
File Name: pred.py
Author: GID5564
Description: 预测数据
Version: 1.0
Created Time: 23/04/24-19:38:56
※※※※※※※※※※※※※※※※※※※※※※※※※※※※※※※※※※※※※※※'''
  
#!/usr/bin/python
# -*- coding: UTF-8 -*-

# %% 导入必要的包 
import tensorflow as tf
import numpy as np
import cv2
import os

from model import create_model

IMG_EXTENSIONS = [
    '.jpg', '.JPG', '.jpeg', '.JPEG',
    '.png', '.PNG', '.ppm', '.PPM', '.bmp', '.BMP', '.tiff'
]

#判断图片
def is_image_file(filename):
    return any(filename.endswith(extension) for extension in IMG_EXTENSIONS)
    
def predicts(image_path):
    """
    图片预测
    :param image_path: 图片地址
    """
    if is_image_file(image_path):
        # 设置待识别的图片
        img=cv2.imread(image_path,0) 
        imgs = np.array([img])
    else:
        print(f"无效图片: {image_path}")
        return 0
    
    """
    多个图片
    #imgs = np.array([img1,img2])
    """
    # 构建模型
    model = create_model()
    
    # 加载前期训练好的权重
    # 加载模型权重时忽略未找到的变量警告
    status = model.load_weights('checkpoint/char_checkpoint').expect_partial()

    # 读出图片分类
    class_name = np.load('class_name.npy')
    
    # 预测图片，获取预测值
    predicts = model.predict(imgs) 
    
    results = [] # 保存结果的数组
    for predict in predicts: #遍历每一个预测结果
        index = np.argmax(predict) # 寻找最大值
        result = class_name[index] # 取出字符
        results.append(result)
    print(results)


if __name__ == "__main__":
    image="./images/img1.png"
    predicts(image)























